<template>
	<view class="container">
		<!-- 状态栏占位 -->
		<view class="status-bar" :style="{ height: statusBarHeight + 'px' }"></view>
		
		<!-- 顶部搜索栏 -->
		<view class="search-header">
			<view class="back-btn" @tap="goBack">
				<!-- <text class="iconfont icon-arrow-left"></text> -->
                <uni-icons type="left" size="20"></uni-icons>
			</view>
			<view class="search-box">
				<text class="iconfont icon-segi-icon-search"></text>
				<input 
					type="text"
					v-model="keyword"
					placeholder="搜索帖子"
					confirm-type="search"
					@confirm="handleSearch"
				/>
				<text 
					class="clear-btn" 
					v-if="keyword"
					@tap="clearKeyword"
				>×</text>
			</view>
			<view class="search-btn" @tap="handleSearch">搜索</view>
		</view>
		
		<!-- 历史记录 -->
		<view class="history-section" v-if="!searchResults.length">
			<view class="section-header">
				<text class="title">历史记录</text>
				<text class="clear-all" @tap="clearHistory">
					<text class="iconfont icon-icon_delete"></text>
				</text>
			</view>
			<view class="history-list">
				<view 
					class="history-item"
					v-for="(item, index) in searchHistory"
					:key="index"
					@tap="useHistoryKeyword(item)"
				>
					{{ item }}
				</view>
			</view>
		</view>
		
		<!-- 搜索结果 -->
		<scroll-view 
			class="search-results" 
			scroll-y="true"
			:style="{ height: 'calc(100vh - var(--status-bar-height) - 112rpx)' }"
			v-if="searchResults.length"
		>
			<post-waterfall :posts="searchResults" />
		</scroll-view>
		
		<!-- 无结果提示 -->
		<view 
			class="no-result" 
			v-if="hasSearched && !searchResults.length"
		>
			<text>暂无相关内容</text>
		</view>
		
		<!-- 清空历史确认弹窗 -->
		<message-box
			ref="clearHistoryMessageBox"
			title="清空历史"
			message="确定要清空搜索历史吗？"
			cancelText="取消"
			confirmText="清空"
			confirmColor="#ff6b6b"
			@confirm="confirmClearHistory"
		/>
	</view>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { api } from '@/utils/request'
import PostWaterfall from '@/components/PostWaterfall.vue'
import MessageBox from '@/components/MessageBox.vue'
import storages from '@/utils/storages'

const keyword = ref('')
const searchResults = ref([])
const searchHistory = ref([])
const hasSearched = ref(false)
const loading = ref(false)

// 获取状态栏高度
const statusBarHeight = ref(uni.getSystemInfoSync().statusBarHeight)

// 消息弹窗
const clearHistoryMessageBox = ref(null)

// 从本地存储获取搜索历史
const getSearchHistory = () => {
	const history = uni.getStorageSync(storages.UserInfo.searchHistory) || []
	searchHistory.value = history
}

// 保存搜索历史
const saveSearchHistory = (kw) => {
	if(!kw) return
	let history = uni.getStorageSync(storages.UserInfo.searchHistory) || []
	// 去重
	history = history.filter(item => item !== kw)
	// 新关键词放在前面
	history.unshift(kw)
	// 最多保存10条
	history = history.slice(0, 10)
	uni.setStorageSync(storages.UserInfo.searchHistory, history)
	searchHistory.value = history
}

// 清空历史记录
const clearHistory = () => {
	clearHistoryMessageBox.value.show()
}

// 确认清空历史记录
const confirmClearHistory = () => {
	uni.removeStorageSync(storages.UserInfo.searchHistory)
	searchHistory.value = []
}

// 使用历史关键词
const useHistoryKeyword = (kw) => {
	keyword.value = kw
	handleSearch()
}

// 清空关键词
const clearKeyword = () => {
	keyword.value = ''
	searchResults.value = []
	hasSearched.value = false
}

// 搜索处理
const handleSearch = async () => {
	if(!keyword.value.trim() || loading.value) return
	
	loading.value = true
	try {
		const res = await api.request({
			url: '/api/post/search_post/',
			method: 'GET',
			data: {
				keyword: keyword.value.trim(),
				page: 1,
				page_size: 10
			}
		})
		
		if(res.code === 200) {
			searchResults.value = res.data
			hasSearched.value = true
			saveSearchHistory(keyword.value.trim())
		}
	} catch(err) {
		console.error('搜索失败', err)
		uni.showToast({
			title: '搜索失败',
			icon: 'none'
		})
	} finally {
		loading.value = false
	}
}

// 返回上一页
const goBack = () => {
	uni.navigateBack()
}

// 页面加载时获取搜索历史
onMounted(() => {
	getSearchHistory()
})
</script>

<style lang="scss" scoped>
.container {
	min-height: 100vh;
	background: #f5f5f5;
}

// 状态栏样式
.status-bar {
	background: #fff;
	width: 100%;
}

.search-header {
	display: flex;
	align-items: center;
	padding: 20rpx;
	background: #fff;
	position: sticky;
	top: 0;
	z-index: 100;
	box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.04);
	
	.back-btn {
		padding: 10rpx 20rpx;
		margin-right: 10rpx;
		
		.icon-arrow-left {
			font-size: 40rpx;
			color: #333;
		}
	}
	
	.search-box {
		flex: 1;
		height: 72rpx;
		background: #f5f5f5;
		border-radius: 36rpx;
		display: flex;
		align-items: center;
		padding: 0 20rpx;
		
		.icon-search {
			font-size: 32rpx;
			color: #999;
			margin-right: 10rpx;
		}
		
		input {
			flex: 1;
			height: 100%;
			font-size: 28rpx;
			color: #333;
            margin-left: 10rpx;
		}
		
		.clear-btn {
			padding: 0 10rpx;
			color: #999;
			font-size: 40rpx;
		}
	}
	
	.search-btn {
		padding: 0 20rpx;
		font-size: 28rpx;
		color: #666;
	}
}

.history-section {
	padding: 30rpx;
	background: #fff;
	margin-top: 20rpx;
	
	.section-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-bottom: 20rpx;
		
		.title {
			font-size: 28rpx;
			color: #333;
			font-weight: bold;
		}
		
		.clear-all {
			color: #999;
			font-size: 28rpx;
			
			.icon-delete {
				font-size: 32rpx;
			}
		}
	}
	
	.history-list {
		display: flex;
		flex-wrap: wrap;
		gap: 20rpx;
		
		.history-item {
			padding: 10rpx 30rpx;
			background: #f5f5f5;
			border-radius: 30rpx;
			font-size: 24rpx;
			color: #666;
			
			&:active {
				opacity: 0.7;
			}
		}
	}
}

.search-results {
	padding: 20rpx;
	box-sizing: border-box;
	width: 100%;
	overflow-x: hidden;
	height: calc(100vh - var(--status-bar-height) - 112rpx) !important;
}

.no-result {
	text-align: center;
	padding: 100rpx 0;
	color: #999;
	font-size: 28rpx;
}
</style>
